<template>
  <div class="project-application-add-container">
    <BreadCrumbRow/>
    <div class="project-application-add-main">
      <div v-if="projectId">
        <div class="title">项目信息</div>
        <el-form class="form-body" label-width="130">
          <el-form-item label="项目类型：" prop="projectType" class="third_row">
            <span>{{ dicFormatter(options.projectTypeEnum, projectInfo.projectType) }}</span>
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName" class="third_row">
            <span>{{ projectInfo.projectName }}</span>
          </el-form-item>
          <el-form-item label="建设规模" prop="projectScale" class="third_row">
            <span>{{ dicFormatter(options.projectScaleEnum, projectInfo.projectScale) }}</span>
          </el-form-item>

          <el-form-item label="项目单位" prop="projectUnit" class="third_row">
            <span>{{ projectInfo.projectUnitName }}</span>
          </el-form-item>
          <el-form-item label="项目负责人" prop="projectChargePerson" class="third_row">
            <span>{{ projectInfo.projectChargePersonName }}</span>
          </el-form-item>
          <el-form-item label="联系电话" prop="projectTelephone" class="third_row">
            <span>{{ projectInfo.projectTelephone }}</span>
          </el-form-item>

          <el-form-item label="施工单位" prop="constructionUnit" class="third_row">
            <span>{{ projectInfo.constructionUnitName }}</span>
          </el-form-item>
          <el-form-item label="施工单位负责人" prop="constructionChargePerson" class="third_row">
            <span>{{ projectInfo.constructionChargePersonName }}</span>
          </el-form-item>
          <el-form-item label="联系电话" prop="constructionTelephone" class="third_row">
            <span>{{ projectInfo.constructionTelephone }}</span>
          </el-form-item>

          <el-form-item label="建设单位" prop="supervisionUnit" class="third_row">
            <span>{{ projectInfo.supervisionUnitName }}</span>
          </el-form-item>
          <el-form-item label="建设单位负责人" prop="supervisionChargePerson" class="third_row">
            <span>{{ projectInfo.supervisionChargePersonName }}</span>
          </el-form-item>
          <el-form-item label="联系电话" prop="supervisionTelephone" class="third_row">
            <span>{{ projectInfo.supervisionTelephone }}</span>
          </el-form-item>

          <el-form-item label="开工日期" prop="planStartTime" class="third_row">
            <span>{{ projectInfo.planStartTime }}</span>
          </el-form-item>
          <el-form-item label="竣工日期" prop="planEndTime" class="third_row">
            <span>{{ projectInfo.planEndTime }}</span>
          </el-form-item>
          <el-form-item label="施工航站楼" prop="code" class="all_row" style="vertical-align: top;">
            <span>{{ dicFormatter(options.locationEnum, projectInfo.location) }}</span>
          </el-form-item>
          <el-form-item label="备注" prop="remark" class="all_row">
            <!-- <span>{{ projectInfo.remark }}</span> -->
            <div class="remak-box">{{ projectInfo.remark }}</div>
          </el-form-item>
          <el-form-item label="附件" prop="files" class="all_row">
            <HyUpload :file-list="projectInfo.files" :disabled="true"/>
          </el-form-item>
        </el-form>
      </div>

      <div class="title">每日施工申请</div>
      <el-form ref="formRef" label-width="130" :model="form" :rules="rules" style="width: 100%">
        <el-row>
          <el-col :span="10">
            <el-form-item label="申请施工日期" prop="applyConstructionTime" class="third_row">
              <el-date-picker v-if="editable" type="date" v-model="form.applyConstructionTime" placeholder="请选择" value-format="YYYY-MM-DD HH:mm:ss" :shortcuts="shortcuts"/>
              <span v-else>{{ form.applyConstructionTime.slice(0,10) }}</span>
            </el-form-item>
            <el-form-item label="附件" prop="files" class="all_row">
              <HyUpload :file-list="form.files" :disabled="!editable"/>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="施工作业内容" prop="constructionOperationContent" class="third_row">
              <el-input
                v-if="editable"
                type="textarea"
                :rows="3"
                :maxlength="200"
                show-word-limit
                placeholder="请输入内容"
                v-model="form.constructionOperationContent">
              </el-input>
              <span v-else>{{ form.constructionOperationContent }}</span>
              </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>

      <div class="title">每日施工区域</div>
      <AreaTable title="施工区域列表" :tableData="form.areas" :options="options" :disabled="!editable" :location="projectInfo.location"/>
      
      <div class="title">每日施工特种作业人员</div>
      <UserTable v-for="(value, key) in specialList" :key="key" :title="dicFormatter( options.specialOperationEnum, key)" :tableData="value"
                 :personType="options.personTypeEnum[0].value" @onsubmit="addUserSubmit"
                 @ondelete="deleteUser" :options="options" :disabled="!editable" :operators="form.operators" notRequireFile/>

      <div class="title">每日施工人员</div>
      <UserTable title="施工人员列表" :tableData="otherConstructionUsers" :personType="options.personTypeEnum[1].value" @onsubmit="addUserSubmit"
                 @ondelete="deleteUser" :options="options" :disabled="!editable" notRequireFile/>
      <div class="title">施工管理规定</div>
      <div style="padding-bottom: 20px;">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;提交视为申请单位已对施工人员进行了《咸阳机场施工管理规定》、《航站楼施工管理规定》和《隔离区证件管理规定》的相关培训和安全告知。承诺我单位在现场实施作业时有专人进行施工全程监管，对施工中出现的任何安全问题全权承担安全主体管理责任。
      </div>
      <div class="operate-fixed">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <template v-if="pageType==='添加'">
          <el-button type="primary" size="large" @click="handleTemplate">暂存</el-button>
          <el-button type="primary" size="large" @click="handleCreate" v-loading="loading" :disabled="loading">提交</el-button>
        </template>
         <template v-if="pageType==='编辑'">
          <el-button type="primary" size="large" @click="editSubmit" v-loading="loading" :disabled="loading">提交</el-button>
        </template>

        <template v-if="pageType==='审核'">
          <el-button type="danger" size="large" @click="openRejectDia">驳回</el-button>
           <el-button type="primary" size="large" @click="passSubmit" v-loading="examineLoading" :disabled="examineLoading">通过</el-button>
        </template>
      </div>
    </div>
    <edit-dialog tilte="驳回" :centerDialogVisible="rejectVisible" width="500" @Cancel="rejectVisible=false" @Submit="rejectSubmit" :confirmLoading="rejectLoading">
      <template #content>
        <el-form ref="rejectFormRef" :model="rejectForm" :rules="rejectRules">
          <el-form-item prop="rejectReason" label="审批意见：">
            <el-input
              type="textarea"
              :rows="10"
              maxlength="200"
              show-word-limit
              placeholder="请输入内容"
              v-model="rejectForm.rejectReason">
            </el-input>
          </el-form-item>
        </el-form>
      </template>
    </edit-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import BreadCrumbRow from "@/components/BreadCrumbRow";
import UserTable from "./UserTable.vue";
import AreaTable from "./AreaTable.vue";
import HyUpload from "./HyUpload.vue";
// import AddApproveFlow from "@/views/construction/project-application/componens/AddApproveFlow";
import store from "@/store";
import {getResource} from "@/api/resource";
// import {approveProject, createProject, getCommonProcessNodes, getProjectDetail} from "@/api/construction-project/projectManage";
import {getCommonProcessNodes, getProjectDetail} from "@/api/construction-project/projectManage";
import { addApply, editApply,getApplyDetail,examine } from "@/api/construction-daily/daily";
// import {dicFormatter, matchProjectState, ProjectFormType, stateEnum} from "@/views/construction/project-application/projectUtil";
import {dicFormatter, matchProjectState, ProjectFormType} from "../projectUtil";
// import ReviewProject from "@/views/construction/project-application/componens/ReviewProject";
// import ApproveRecord from "@/views/construction/project-application/componens/ApproveRecord";
// import DelayRecord from "@/views/construction/project-application/componens/DelayRecord";
import HistoryApproveFlowAxis from "@/views/construction/project-application/componens/HistoryApproveFlowAxis";
// import {getUserInfo} from "@/api/eqpt/houseManger";
import EditDialog from "../../../event/components/modal.vue";

export default {
  name: "ProjectForm",
  components: {HistoryApproveFlowAxis, HyUpload, AreaTable, UserTable, BreadCrumbRow,EditDialog},
  props: {
    pageType: {
      type: String,
      default: ProjectFormType.ADD
    }
  },
  provide() {
    return {
      options: this.options,
      pageType: this.pageType
    }
  },
  data() {
    return {
      rejectForm: {},
      rejectRules: {
        rejectReason: [
          {required: true, message: '请输入', trigger: ['blur', 'change']},
        ]
      },
      loading: false, // 提交loading
      examineLoading: false, //审核通过
      rejectLoading: false, // 驳回提交
      projectInfo: {},
      form: {
        applyConstructionTime:'',
        constructionOperationContent:'',
        files: [],
        areas: [],
        operators: [],
      },
      projectChargePersonListData: [],
      constructionChargePersonListData: [],
      supervisionChargePersonListData: [],
      options: {
        projectTypeEnum: [],
        locationEnum: [],
        specialOperationEnum: [],
        projectScaleEnum: [],
        personTypeEnum: [
          {label: '特种作业人员', value: '1'},
          {label: '施工人员', value: '2'},
        ],
        personSourceEnum: [
          {label: '内部人员', value: '1'},
          {label: '外部人员', value: '2'},
        ],
        companyUnitTreeData: [],
        nodeTypeEnum: [
          {label: '填写节点', value: '1'},
          {label: '审批节点', value: '2'},
        ],
        approveNodeTypeEnum: [
          {label: '上传培训记录', value: '1'},
          {label: '审批培训记录', value: '2'},
        ],
        projectWorkTypeOptions: [], // 特种作业工作类型
        // 固定状态列表
        // stateEnum: stateEnum,
        // 审批类型，1 ：串行审批 2：并行或签 3 并行 会签
        // approvalTypeTree: [
        //   {
        //     label: '并行审批',
        //     children: [
        //       {
        //         label: '会签(需所有负责人通过)',
        //         value: 3
        //       },
        //       {
        //         label: '或签(一名负责人通过或驳回即可)',
        //         value: 2
        //       },
        //     ]
        //   },
        //   {
        //     label: '串行审批',
        //     value: 1
        //   }
        // ],
        companyUnitTreeProps: {
          label: 'organizationName',
          disabled: (data, node) => {
            return data.disabled
          }
        },
        personTreeProps: {
          label: 'userName',
          disabled: (data, node) => {
            return false
          }
        },
      },
      rules: {
        applyConstructionTime: [
          {required: true, message: '请选择', trigger: ['blur', 'change']},
        ],
        constructionOperationContent: [
          {required: true, message: '请输入', trigger: ['blur', 'change']},
        ],
      },
      dicFormatter,
      matchProjectState,
      ProjectFormType,
      applyId: undefined,
      projectId:undefined,
      rejectVisible: false,
      shortcuts:  [{
            text: '今天',
            value: new Date()
          }]
    }
  },
  computed: {
    editable() {
      if(this.pageType==="添加"|| this.pageType==='编辑'){
        return true
      }else{
        return false
      }
    },
    userInfo() {
      return store.state.user.userInfo
    },
    // 施工人员
    otherConstructionUsers() {
      let users = this.form.operators.filter(item => item.personType === this.options.personTypeEnum[1].value)
      console.log(users,'施工')
      return users
    },
    // 特殊作业人员
    specialList() {
      let users = this.form.operators.filter(item => item.personType === this.options.personTypeEnum[0].value)
      let res = users.reduce((obj, item) => {
        let arr = obj[item.specialJobType]
        if (arr) {
          arr.push(item)
        } else {
          obj[item.specialJobType] = [item]
        }
        return obj
      }, {})
      if (!Object.keys(res).length) {
        return {
          UseFire: [],
        }
      } else {
        console.log(res,'特殊')
        return res
      }
    },
  },
  created() {
    this.initQuery()
    this.initOptions()
  },
  methods: {
    initQuery() {
      // 如果有项目信息
      if (this.$route.query.projectId!=='undefined') {
        this.projectId=this.$route.query.projectId;
        getProjectDetail(this.$route.query.projectId).then(res => {
          let {project,areas,operators} = res.data;
          this.projectInfo = {...project}
          if(this.pageType==='添加'){
            this.form.areas = areas;
            this.form.operators = operators;
          }
        })
      };
      if (this.$route.query.id) {
        this.applyId= this.$route.query.id;
        getApplyDetail(this.$route.query.id).then(res => {
          const { dailyConstruction,project,...more } = res.data;
          this.form = {...dailyConstruction,...more };
        })
      } else {
        let temp = localStorage.getItem('daily_apply')
        if (temp) {
          this.form.applyConstructionTime = JSON.parse(temp).applyConstructionTime;
          this.form.constructionOperationContent = JSON.parse(temp).constructionOperationContent;
          this.form.files = JSON.parse(temp).files
        }
      }
    },
    initOptions() {
      const tree = store.getters['user/getOrganTree']
      this.options.companyUnitTreeData = tree

      Promise.all([
        getResource('CM_PROJECT_TYPE'),
        getResource('terminals'),
        getResource('SPECIAL_OPERATION'),
        getResource('PROJECT_SCALE'),
        getResource('CM_PROJECT_PROCESS_UPLOAD'),
        getResource('CM_PROJECT_WORK_TYPE'),
        getCommonProcessNodes(),
      ]).then((
        [
          CM_PROJECT_TYPE,
          terminals,
          SPECIAL_OPERATION,
          PROJECT_SCALE,
          CM_PROJECT_PROCESS_UPLOAD,
          CM_PROJECT_WORK_TYPE,
          commonProcessNodes
        ]) => {
        this.options.projectTypeEnum = CM_PROJECT_TYPE.data.properties.meta
        this.options.locationEnum = terminals.data.properties.meta
        this.options.specialOperationEnum = SPECIAL_OPERATION.data.properties.meta
        this.options.projectScaleEnum = PROJECT_SCALE.data.properties.meta
        this.options.approveNodeTypeEnum = CM_PROJECT_PROCESS_UPLOAD.data.properties.meta
        this.options.projectWorkTypeOptions = CM_PROJECT_WORK_TYPE.data.properties.meta
        this.options.commonProcessNodes = commonProcessNodes.data
      })
    },
    handleCreate() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.loading = true
          let {files, ...more} = this.form
          let newForm = {
            creator: {
              id: this.userInfo.userId,
              name: this.userInfo.name,
              organId: this.userInfo.organId,
              organName: this.userInfo.organName,
            },
            ...more,
            files: files && files.length ? files : undefined,
            projectId: this.projectId?this.projectId:undefined,
          }
          addApply(newForm).then(()=>{
            localStorage.removeItem('daily_apply')
            this.$message.success('添加成功')
            this.$router.back()
          }).catch((err)=>{
            ElMessage.error(err?.message || '操作失败')
          }).finally(()=>{
            this.loading = false
          })
        }
      })
    },

    editSubmit() {
      try {
        this.loading = true
        this.$refs.formRef.validate(async valid => {
          if (valid) {
            // this.validData()
            let {files, ...more} = this.form
            let newForm = {
              id:this.applyId,
              creator: {
                id: this.userInfo.userId,
                name: this.userInfo.name,
                organId: this.userInfo.organId,
                organName: this.userInfo.organName,
              },
              ...more,
              files: files && files.length ? files : undefined,
              projectId: this.projectId?this.projectId:undefined,
            }
            await editApply(newForm)
            localStorage.removeItem('daily_apply')
            this.$message.success('编辑成功')
            this.$router.back()
          }
        })
      } finally {
        this.loading = false
      }
    },
    openRejectDia() {
      this.rejectVisible=true;
    },

    // 审核通过
    passSubmit() {
      this.examineLoading= true;
      examine({
        id: this.applyId,
        state: '3',
        lastMender:{
          id: this.userInfo.userId,
          name: this.userInfo.name,
          organId: this.userInfo.organId,
          organName: this.userInfo.organName,
        }
      }).then(()=>{
          this.$router.back()
      }).finally(()=>{
        this.examineLoading= false;
      })
    },
    rejectSubmit(){
      this.$refs.rejectFormRef.validate((valid) => {
        if (valid) {
          this.rejectLoading=true;
          examine({
            id: this.applyId,
            reasonRejection: this.rejectForm.rejectReason,
            state: '2',
            lastMender:{
              id: this.userInfo.userId,
              name: this.userInfo.name,
              organId: this.userInfo.organId,
              organName: this.userInfo.organName,
            }
          }).then(()=>{
            this.rejectVisible=false;
            this.$router.back()
          }).finally(()=>{
            this.rejectLoading=false;
          })
        }
      });
    },

    // validData() {
    //   let {planStartTime, planEndTime,} = this.form
    //   let startDate = new Date(planStartTime)
    //   let endDate = new Date(planEndTime)
    //   if (startDate.getTime() >= endDate.getTime()) {
    //     this.$message.error('开工时间不能大于竣工时间')
    //     throw new Error('开工时间不能大于竣工时间')
    //   }
    // },
   
    handleTemplate() {
      localStorage.setItem('daily_apply', JSON.stringify(this.form))
      this.$message.success('保存成功')
    },
    handleCancel() {
      this.$router.back()
    },
    // openApproveProject() {
    //   this.$refs.reviewProjectRef.open(this.form)
    // },
    // handlePass() {
    //   this.$refs.addApproveFlowRef.open({
    //     projectInfo: this.form,
    //     resolve: (approveInfo) => {
    //       let newForm = {
    //         approver: {
    //           id: this.userInfo.userId,
    //           name: this.userInfo.name,
    //           organId: this.userInfo.organId,
    //           organName: this.userInfo.organName,
    //         },
    //         processInfoAppendScheme: approveInfo,
    //         projectId: this.form.id,
    //         status: 1,
    //         change: this.form.change,
    //         examineOpinion: undefined,
    //       }
    //       approveProject(newForm).then(res => {
    //         this.$message.success('操作成功')
    //         this.$router.back()
    //       })
    //     }
    //   })
    // },
    addUserSubmit(obj) {
      if (Array.isArray(obj)) {
        this.form.operators.push(...obj)
      } else {
        this.form.operators.push(obj)
      }
    },
    deleteUser(row) {
      let index = this.form.operators.findIndex(item => item === row);
      this.form.operators.splice(index, 1)
    },

   
    // companyUnitChange(refName, setFieldName, personListFieldName) {
    //   let ref = this.$refs[refName]
    //   let checkedNodes = ref.getCheckedNodes()
    //   if (checkedNodes.length) {
    //     this.form[setFieldName] = checkedNodes[0].organizationName
    //     getUserInfo({groupIds: checkedNodes.map(item => item.organizationId)}).then(res => {
    //       this[personListFieldName] = res.data
    //     })
    //   }
    // },
    // personChange(refName, setFieldName) {
    //   let ref = this.$refs[refName]
    //   let checkedNodes = ref.getCheckedNodes()
    //   if (checkedNodes.length) {
    //     this.form[setFieldName] = checkedNodes[0].userName
    //   }
    // }
  }
}
</script>

<style lang="less" scoped>
.remak-box {
  word-wrap: break-word;
}
.project-application-add-container {
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  // background: rgba(255, 205, 205, 0.49);
  .project-application-add-main {
    flex: 1;
    overflow: auto;
    padding: 20px 30px 90px 20px;
    background: white;
    margin-top: 20px;
    box-sizing: border-box;
    border-radius: 5px;
    .title {
      position: relative;
      margin-bottom: 20px;
      padding-left: 13px;
      font-size: 18px;
      font-weight: 500;
      &::before {
        position: absolute;
        content: '';
        left: 0;
        top: 1px;
        height: 23px;
        border-radius: 2px;
        width: 6px;
        background: #2F7DF1;
      }
    }
    .form-body {
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;
      .third_row {
        width: 31%;
        min-width: 300px;
        ::v-deep .el-form-item__content > * {
          width: 100% !important;
        }
      }
      .all_row {
        width: 93%;
        ::v-deep .el-form-item__content > * {
          width: 100% !important;
        }
      }
    }
  }
  .operate-fixed {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 0 35%;
    z-index: 10;
    position: absolute;
    left: 20px;
    right: 20px;
    bottom: 20px;
    height: 80px;
    background: white;
    border-top: 1px solid #d7d7d7;
  }

}
</style>
